package com.heima.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.BehaviorConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.admin.dtos.AuthDto;
import com.heima.model.behavior.dtos.CollectionBehaviorDto;
import com.heima.model.behavior.dtos.UserRelationDto;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserFan;
import com.heima.model.user.pojos.ApUserFollow;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.user.mapper.ApUserFanMapper;
import com.heima.user.mapper.ApUserFollowMapper;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import com.heima.utils.thread.AppThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;


@Service
@Transactional
@Slf4j
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser> implements ApUserService {
    @Autowired
    private ApUserRealnameMapper apUserRealnameMapper;
    @Autowired
    private ApUserFollowMapper apUserFollowMapper;
    @Autowired
    private ApUserFanMapper apUserFanMapper;
    @Autowired
    private CacheService cacheService;


    @Override
    public ResponseResult getList(AuthDto dto) {
        if (dto==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.setPage(Optional.ofNullable(dto.getPage()).orElse(1));
        dto.setSize(Optional.ofNullable(dto.getSize()).orElse(5));
        Page<ApUserRealname> pageRes = apUserRealnameMapper.selectPage(
                new Page<ApUserRealname>(dto.getPage(), dto.getSize()),
                Wrappers.lambdaQuery(ApUserRealname.class)
                        .eq(dto.getStatus() != null, ApUserRealname::getStatus, dto.getStatus())
        );
        PageResponseResult res = new PageResponseResult(dto.getPage(), dto.getSize(), ((int) pageRes.getTotal()));
        return res.ok(pageRes.getRecords());
    }

    /**
     * 人工审核 用户认证
     * @param dto
     * @return
     */
    @Override
    public ResponseResult authFail(AuthDto dto) {
        if (dto==null || dto.getId()==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUserRealname apUserRealname = apUserRealnameMapper.selectById(dto.getId());
        apUserRealname.setStatus(((short) 2));
        apUserRealname.setReason("审核材料内容不符合规定,审核失败！");
        apUserRealnameMapper.updateById(apUserRealname);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 用户关注 / 取消关注
     * @param dto
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult userFollow(UserRelationDto dto) {
        if (dto==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //当前用户
        ApUser user = AppThreadLocal.getUser();
        if (user==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NO_OPERATOR_AUTH);
        }
        Short operation = dto.getOperation();
        String k = BehaviorConstants.USER_BEHAVIOR_FOLLOW+dto.getAuthorId();
        Integer followUserId = dto.getAuthorId();
        Integer apUserId = user.getId();
        if (operation==0) {
            //关注
//            ApUserFollow apUserFollow = new ApUserFollow();
//            apUserFollow.setCreatedTime(new Date());
//            apUserFollow.setUserId(user.getId());
//            apUserFollow.setFollowId(dto.getAuthorId());
//            apUserFollow.setLevel(((short) 0));
//            apUserFollow.setIsNotice(((short) 0));

            //粉丝
//            ApUserFan apUserFan = new ApUserFan();
//            apUserFan.setFansId(user.getId());
//            apUserFan.setUserId(dto.getAuthorId());
//            apUserFan.setFansName(user.getName());
//            apUserFan.setLevel(((short) 0));
//            apUserFan.setIsDisplay(((short) 1));
//            apUserFan.setCreateTime(new Date());
//            apUserFan.setIsShieldComment(((short) 0));
//            apUserFan.setIsShieldLetter(((short) 0));
//
//            int insert = apUserFollowMapper.insert(apUserFollow);
//            if (insert<=0) {
//                throw new RuntimeException();
//            }
//            int insert1 = apUserFanMapper.insert(apUserFan);
//            if (insert1<=0) {
//                throw new RuntimeException();
//            }
//            cacheService.hPut(k, user.getId().toString(), JSON.toJSONString(apUserFollow));
            // 将对方写入我的关注中
            cacheService.zAdd(BehaviorConstants.APUSER_FOLLOW_RELATION + apUserId, followUserId.toString(), System.currentTimeMillis());
            // 将我写入对方的粉丝中
            cacheService.zAdd(BehaviorConstants.APUSER_FANS_RELATION+ followUserId, apUserId.toString(), System.currentTimeMillis());
        }else {
            //取消
            //删除关注
//            int delete = apUserFollowMapper.delete(Wrappers.lambdaQuery(ApUserFollow.class).eq(ApUserFollow::getFollowId, dto.getAuthorId()).eq(ApUserFollow::getUserId, user.getId()));
//            if (delete<=0) {
//                throw new RuntimeException();
//            }
//            //删除粉丝
//            int delete1 = apUserFanMapper.delete(Wrappers.lambdaQuery(ApUserFan.class).eq(ApUserFan::getUserId, dto.getAuthorId()).eq(ApUserFan::getFansId, user.getId()));
//            if (delete1<=0) {
//                throw new RuntimeException();
//            }
//            cacheService.hDelete(k, user.getId().toString());
            cacheService.zRemove(BehaviorConstants.APUSER_FOLLOW_RELATION + apUserId, followUserId.toString());
            cacheService.zRemove(BehaviorConstants.APUSER_FANS_RELATION + followUserId, apUserId.toString());
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }



    @Override
    public ResponseResult authPass(AuthDto dto) {
        if (dto==null || dto.getId()==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        ApUserRealname apUserRealname = apUserRealnameMapper.selectById(dto.getId());
        //审核成功
        apUserRealname.setStatus(((short) 9));
        apUserRealname.setReason("");
        apUserRealnameMapper.updateById(apUserRealname);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * app端登录功能
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {
        //1.正常登录 用户名和密码
        if(StringUtils.isNotBlank(dto.getPhone()) && StringUtils.isNotBlank(dto.getPassword())){
            //1.1 根据手机号查询用户信息
            ApUser dbUser = getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getPhone, dto.getPhone()));
            if(dbUser == null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"用户信息不存在");
            }

            //1.2 比对密码
            String salt = dbUser.getSalt();
            String password = dto.getPassword();
            String pswd = DigestUtils.md5DigestAsHex((password + salt).getBytes());
            if(!pswd.equals(dbUser.getPassword())){
                return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }

            //1.3 返回数据  jwt  user
            String token = AppJwtUtil.getToken(dbUser.getId().longValue());
            Map<String,Object> map = new HashMap<>();
            map.put("token",token);
            dbUser.setSalt("");
            dbUser.setPassword("");
            map.put("user",dbUser);

            return ResponseResult.okResult(map);
        }else {
            //2.游客登录
            Map<String,Object> map = new HashMap<>();
            map.put("token",AppJwtUtil.getToken(0L));
            return ResponseResult.okResult(map);
        }


    }
}
